package config

import java.io.{IOException, InputStream}
import java.security.KeyStore

import javax.net.ssl.SSLContext
import org.apache.http.conn.ssl.SSLContexts

class SSLProperties (mchId:String, mchKey:String){
  /**
   * 证书内容
   */
  var sslContext:SSLContext = _

  /**
   * 初始化证书
   *
   * @return
   */
  def initSSLContext(keyPath: String): SSLContext = {
    var inputStream:InputStream = this.getClass.getResourceAsStream(keyPath)
    try {
      val keystore = KeyStore.getInstance("PKCS12")
      val partnerId2charArray = mchId.toCharArray
      keystore.load(inputStream, partnerId2charArray)
      this.sslContext = SSLContexts.custom.loadKeyMaterial(keystore, partnerId2charArray).build
      this.sslContext
    } catch {
      case e: Exception => e.printStackTrace()
        throw new RuntimeException("证书文件有问题，请核实！", e)
    } finally try inputStream.close()
    catch {
      case e: IOException => e.printStackTrace()
    }
  }
}
